<template>
  <div >
    <div v-if="messageStatus">
        <n-card title="优惠券插件" header>
        <div class="header">
            <div style="display: flex;gap:12px">
            <NButton type="primary" @click="onClickAdd">
                添加优惠券
            </NButton>
            <NButton type="primary" @click="jiluShow=true">
                领取记录
            </NButton>
            </div>
            <div>
            <n-input-group>
                <n-input v-model:value="params.keyword" clearable placeholder="请输入插件关键词" :style="{ width: '100%' }" />
                <n-button @click="List" type="primary" ghost>
                    搜索
                </n-button>
                </n-input-group>
            </div>
        </div>
        </n-card>
        <div class="box" :style="'height:'+innerHeights">
        <!-- 数据表 -->
          <div class="table-box">
              <n-data-table
                  striped 
                  :loading="messageParams.loading"
                  ref="table"
                  :columns="columns"
                  :data="data"
              />
          </div> 
            

        </div>

         <div class="pagination">
                <div>共{{pagination.total}}条数据</div>
                <div>
                <n-pagination
                :page="params.pageNum"
                :page-size="params.pageSize"
                :item-count="pagination.total"
                size="medium"
                show-size-picker
                :page-slot="8"
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
                />
                </div>
            </div>
    </div>

    <div v-else class="Message">
        <n-result
            status="403"
            title="403 禁止访问"
            description="总有些门是对你关闭的"
        >
            <template #footer>
            <n-button @click="goTo('/pluginAdmin/all')">去充钱</n-button>
            </template>
        </n-result>
    </div>

  <yingModal :width="'1000px'" :height="'600px'" :title="popTitle" @close="showModal=false" @confirm="submitCallback" :SkuShow="showModal" >
    <template #content>
        <n-form
          ref="formRef"
          :model="formValue"
          :rules="rules"
        >
          <n-form-item  label="优惠券类型" path="type">
            <n-select
              v-model:value="formValue.type"
                
                filterable 
                placeholder="请选择类型"
                :options="typeOptions"
                clearable
              />
          </n-form-item>
          <n-form-item  label="领取方式" path="condition">
            <n-select
              v-model:value="formValue.condition"
               
                filterable 
                placeholder="请选择类型"
                :options="typeOptions1"
                clearable
              />
          </n-form-item>
           <n-form-item v-if="formValue.condition == '新人发放' || formValue.condition == '弹窗发放'" label="图片" path="image">
            <div @click="uploadShow=true" v-if="formValue.image" style="height:135px;width:100px;overflow: hidden;display: flex;padding:12px;
                justify-content: center; align-items: center;">
                <n-image
                :preview-disabled="true"
                style="object-fit: contain;display: flex;
                    justify-content: center;
                    align-items: center;"
                :src="Https()+formValue.image"/>
            </div>
            <div v-else @click="uploadShow=true" class="imageUpload">
              <n-icon size="24" color="rgb(49, 108, 114)">
                <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 16 16"><g fill="none"><path d="M8 2.5a.5.5 0 0 0-1 0V7H2.5a.5.5 0 0 0 0 1H7v4.5a.5.5 0 0 0 1 0V8h4.5a.5.5 0 0 0 0-1H8V2.5z" fill="currentColor"></path></g></svg>
              </n-icon>
            </div>
          </n-form-item>
          <n-form-item label="指定物品(非必选)" >
            <n-select
              v-model:value="formValue.item_id"
                filterable 
                label-field="goodsName"
                value-field="goods_id"
                placeholder="请选择物品"
                :options="goodsList"
                clearable
              />
          </n-form-item>
           
          <n-form-item label="标题" path="title">
            <n-input v-model:value="formValue.title" placeholder="请输入标题" />
          </n-form-item>
           <n-form-item v-if="formValue.condition == '口令发放'" label="口令" path="score">
            <n-input v-model:value="formValue.score" placeholder="请输入口令" />
          </n-form-item>
           <n-form-item label="优惠券面额" path="moneys">
            <n-input v-model:value="formValue.moneys" placeholder="请输入优惠券面额" />
          </n-form-item>
           <n-form-item v-if="formValue.type != '2'" label="满多少" path="min_money">
            <n-input v-model:value="formValue.min_money" placeholder="请输入满多少" />
          </n-form-item>
           <n-form-item label="每人最多领取几张" path="max_number">
            <n-input v-model:value="formValue.max_number" placeholder="请输入每人最多领取几张" />
          </n-form-item>

           <n-form-item label="总共发放数量" path="numbers">
            <n-input v-model:value="formValue.numbers" placeholder="请输入总共发放数量" />
          </n-form-item>

          <n-form-item label="开始时间" path="numbers">
             <n-date-picker v-model:value="formValue.startTime" placeholder="请选择开始时间" type="datetime" clearable />
          </n-form-item>

          <n-form-item label="结束时间" path="numbers">
             <n-date-picker v-model:value="formValue.endTime" placeholder="请选择结束时间" type="datetime" clearable />
          </n-form-item>
          <!-- <n-form-item label="已领取数" path="user_number">
            <n-input v-model:value="formValue.user_number" placeholder="请输入已领取数" />
          </n-form-item>

          <n-form-item label="已使用数量" path="user_use">
            <n-input v-model:value="formValue.user_use" placeholder="请输入已使用数量" />
          </n-form-item> -->
          
          <n-form-item label="领取说明" >
            <commonEditor style="height:550px" :Image="TextImage" :token="token" @uploadImage="uploadImage" :value="formValue.content" @change="getEditorValue" />
          </n-form-item>
          
          
          
          <n-form-item v-if="popTitle == '编辑'" label="状态">
            <n-switch v-model:value="formValue.status">
              <template #checked>
                启动
              </template>
              <template #unchecked>
                禁用
            </template>
            </n-switch>
          </n-form-item>
        </n-form>
    </template>
  </yingModal>

  
    <yingModal  :title="'文件管理'" @close="uploadShow=false" @confirm="uploadShow=false" :SkuShow="uploadShow" >
      <template #content>
        <Upload type="1" @selectImage="selectImageFun"/>
      </template>
  </yingModal>

   <yingModal  :title="'文件管理'" @close="jiluShow=false" @confirm="jiluShow=false" :SkuShow="jiluShow" width="1200px" >
      <template #content>
        <div class="table-box" style="height:500px">
              <n-data-table
                  striped 
                  :loading="messageParams.loading"
                  ref="table"
                  :columns="columns1"
                  :data="userCoupons"
              />
          </div> 

          <div class="pagination">
                <div>共{{pagination.total}}条数据</div>
                <div>
                <n-pagination
                :page="params.pageNum"
                :page-size="params.pageSize"
                :item-count="pagination.total"
                size="medium"
                show-size-picker
                :page-slot="8"
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
                />
                </div>
            </div>
      </template>
  </yingModal>
       
  </div>
</template>

<script setup lang="ts">
import { NAvatar, NButton, NImage, NSwitch, NTag  } from 'naive-ui'
import commonEditor from '@/components/common/commonEditor.vue'
import type { FormInst } from 'naive-ui'
import { nextTick, onMounted, ref } from 'vue'
import { Https,setPagination } from "@/utils"
import api from './api'
import Upload from "@/views/upload/index.vue"
import yingModal from '@/components/common/YingModal.vue'
const router = useRouter()
const route = useRoute()
const pluginInfo = ref({})
const messageStatus = ref(false)
const uploadShow = ref(false)
const jiluShow = ref(false)
const typeOptions = ref([
  {
    label:'满减优惠券',
    value:'1'
  },
  {
    label:'直减',
    value:'2'
  }
])
const typeOptions1 = ref([
  {
    label:'新人发放',
    value:'新人发放'
  },
  {
    label:'静默发放',
    value:'静默发放'
  },

  {
    label:'弹窗发放',
    value:'弹窗发放'
  },
  {
    label:'口令发放',
    value:'口令发放'
  }
])
const TextImage = ref('');
const token = ref('')
const innerHeights = ref(0);
onMounted(() => {
    innerHeights.value = String(window.innerHeight - 280)+'px'
    token.value = JSON.parse(localStorage.getItem("vue-naivue-admin_auth"))['token']
    myPluin()
})


const typeImage = ref('')
const uploadImage = () =>{
  typeImage.value = "富文本"
  uploadShow.value = true;
}
const getEditorValue = (data) => {
 
   formValue.value.content = data
}

const selectImageFun =(selectImageList) =>{
  if(typeImage.value == '富文本'){

    TextImage.value = Https() + selectImageList[0];
    uploadShow.value = false;
    return
  }
  formValue.value.image = selectImageList[0];  // 只获取第一张图
  uploadShow.value = false
} 

async function myPluin(){
  const res: any = await api.checkPluginApi({
    plugin_id:route.query.plugin_id,
    user_id:route.query.user_id,
  })
    
  if(res.code == 200 && res.data){
    pluginInfo.value = route.query
    params.value.user_id = route.query.user_id
    params.value.plugin_id = route.query.plugin_id
    messageStatus.value = true;
    List();
    getGoodsList();
    userCouponsList();
  }else{
    messageStatus.value = false;
  }

}
const goodsList = ref([])
async function getGoodsList(){
  const res: any = await api.goodsListApi({
    pageNum: 1,
    pageSize: 300,
  })
    
  if(res.code == 200){
    goodsList.value = res.data.list
  } 
}
const userCoupons = ref([])
async function userCouponsList(){
  const res: any = await api.userCouponsApi({
    pageNum: 1,
    pageSize: 10,
  })
    
  if(res.code == 200){
    userCoupons.value = res.data.list
  } 
}

const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
]


const pagination = ref({
  total:10
  
})
const formRef = ref<FormInst | null>(null);

const showModal = ref(false);
const popTitle:any = ref('添加优惠券');
const params = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  user_id:''
})

const formValue = ref({
  type:null,
    title:"",
    score:"",
    condition:null,
    moneys:"",
    min_money:"",
    max_number:"",
    numbers:"",
    user_number:"",
    user_use:"",
    content:"",
    status:true,
    item_id:"",
    image:''
})

const rules = {
    type: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    condition: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    title: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    score: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    moneys: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    min_money: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    max_number: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    numbers: {
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    content: {
        required: false,
        message: '请输入',
        trigger: 'blur'
    },

}

const columns1 = [
  // {
  //   title: '优惠券ID',
  //   key: 'coupons_id',
  //   ellipsis: {
  //     tooltip: true
  //   }
 
  // },
  
  {
    title: '标题',
    key: 'title',
    // width: 200,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '用户openid',
    key: 'openid',
    // width: 200,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '类型',
    key: 'type',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    render: (item) => setType(item)
    
  },
  {
    title: '口令',
    key: 'score',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
    
  },
  {
    title: '优惠券面额',
    key: 'moneys',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
    
  },
  {
    title: '满多少',
    key: 'min_money',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
  } ,
   {
    title: '发放条件',
     key: 'getCondition',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    // render: (item) => setCondition(item)
  },
   
  {
    title: '状态',
    key: 'status',
    ellipsis: {
      tooltip: true
    },
    render: (item) => setStatus(item)
  },
 
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
  
    render(row) {
      return [
      
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 12px;',
            secondary: true,
            onClick: () => handleOpenRolesSet(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:edit' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },

]

const columns = [
  {
    title: 'id',
    key: 'id',
    ellipsis: {
      tooltip: true
    }
 
  },
  
  {
    title: '标题',
    key: 'title',
    // width: 200,
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '优惠券说明',
    key: 'content',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
    
  },
 
   
  {
    title: '类型',
    key: 'type',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    render: (item) => setType(item)
    
  },
  {
    title: '口令',
    key: 'score',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
    
  },
  {
    title: '优惠券面额',
    key: 'moneys',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
    
  },
  {
    title: '满多少',
    key: 'min_money',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
  },
  {
    title: '每人最多领取几张',
    key: 'max_number',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
  },
  {
    title: '总共发放数量',
    key: 'numbers',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
  },
  {
    title: '已领取数',
    key: 'user_number',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
  },
  {
    title: '已使用数量',
    key: 'user_use',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    render: (item) => setUser_use(item)
  },
  {
    title: '开始时间',
    key: 'startTime',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
  },
  {
    title: '结束时间',
    key: 'endTime',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
  },
   {
    title: '发放条件',
     key: 'condition',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    // render: (item) => setCondition(item)
  },
   
  {
    title: '状态',
    key: 'status',
    ellipsis: {
      tooltip: true
    },
    render: (item) => setStatus(item)
  },
 
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
  
    render(row) {
      return [
      
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 12px;',
            secondary: true,
            onClick: () => handleOpenRolesSet(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:edit' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },

]

function setUser_use(item){
    // console.log(item)
    if(item.user_use)
      return item.user_use
    else
      return 0
}
function setCondition(item){
    // console.log(item)
    if(item.condition == '1')
        return '新人优惠券'
    if(item.condition == '2')
        return '无条件优惠券'
    if(item.condition == '3')
      return '指定优惠券'
}
 
function setType(item){
    // console.log(item)
    if(item.type == '1')
        return '满减优惠券'
    if(item.type == '2')
        return '直减'
    
    
}


function setStatus(item){
    // console.log(item)
    if(item._status == '1')
        return h('span', { style: { color: 'green' } },'正常')
    if(item._status == '2')
      return h('span', { style: { color: 'pink' } },'已领完')
    else
        return h('span', { style: { color: 'red' } },'禁用')
}
const data: any = ref([])

async function handleDelete(id){
  const res: any = await api.DeleteApi({
    id:id
  })
  if(res.code == 200){
    List();
    $message.success('删除成功!')
  }else{
    
  }

}
const messageParams: any = ref({
  show: false,
  status: '403',
  loading: true,
})

const handleOpenRolesSet =(item) =>{
  
    formValue.value = item;
    if(formValue.value.endTime == "None" || formValue.value.endTime == "" || formValue.value.endTime == Node || formValue.value.endTime == "NaT"){
      formValue.value.endTime = ""
      formValue.value.startTime = ""
    }else{
      formValue.value.endTime = new Date(formValue.value.endTime).getTime()
      formValue.value.startTime = new Date(formValue.value.startTime).getTime()
    }

    if(formValue.value._status == '1')
      formValue.value.status = true
    else
      formValue.value.status = false
    formValue.value.type = String(formValue.value.type) 
    formValue.value.score = String(formValue.value.score) 
    formValue.value.moneys = String(formValue.value.moneys) 
    
    formValue.value.max_number = String(formValue.value.max_number) 
    formValue.value.numbers = String(formValue.value.numbers) 
    if(formValue.value.min_money == "None" || formValue.value.min_money == "" || formValue.value.min_money == Node || formValue.value.min_money == "NaT" || formValue.value.min_money == 0 || formValue.value.min_money == "0"){
      formValue.value.min_money = ""
    }else{
      formValue.value.min_money = String(formValue.value.min_money) 
    }
    popTitle.value = '编辑';
    showModal.value = true;
} 

async function List() {
  try {
    messageParams.value.loading = true
    const res: any = await api.ListApi(params.value)
    if (res.code == 200) {
      messageParams.value.loading = false
      pagination.value.total = res.data.total
      data.value = res.data.list
    }
    else {
      messageParams.value.show = false
      messageParams.value.status = '500'
    }
  }
  catch (error) {
    console.error(error)
  }
}
function onClickAdd(){
  popTitle.value = '添加优惠券'
  showModal.value = true
  formValue.value = {
    type:null,
    title:"",
    score:"",
    moneys:"",
    min_money:"",
    max_number:"",
    numbers:"",
    user_number:"",
    user_use:"",
    content:"",
    status:true,
    condition:null,
    item_id:null,
    image:''
  }
}
async function submitCallback() {
    messageParams.value.loading = true
    formRef.value?.validate((errors) => {
        if (!errors) {
        formValue.value.user_id = route.query.user_id
        formValue.value.plugin_id = route.query.plugin_id
        if(popTitle.value == '添加优惠券')
            AddFun();
        else
            EditFun();
        }
        else {
        showModal.value = true
        return 
    
        }
    })
}

async function AddFun(){
    
    const newData =  formValue.value
    if(newData.content == undefined){
      newData.content = ""
    }
    console.log(formValue.value)
    const res: any = await api.AddApi(newData)
    if(res.code == 200){
        List();
        showModal.value = false;
        $message.success('添加成功!')
        
    }else{
        $message.error(res.message)
    }
}

async function EditFun(){
  if(formValue.value.content == undefined){
    formValue.value.content = ""
  }
  const res: any = await api.EditApi(formValue.value)
  if(res.code == 200){
    List();
    $message.success('编辑成功!')
    showModal.value = false;
  }else{
    $message.error(res.message)
  }
}

function pageNext(page){
  params.value.pageNum = page
  List();
}
function sizeNext(size){
    params.value.pageNum = 1
    params.value.pageSize = size
    List();
}


function cancelCallback() {
  List();
  showModal.value = false
}

function goTo(path){
    router.push(path)
}

function toStore(item){
    router.push({
      path:'/plugin/goodsPlugin/index',
      query:{
        user_id:route.query.user_id,
        store_id:item.businessId,
      }
    })
    // router.push('/plugin/goodsPlugin/index')
}
</script>

<style scoped>
 .box {
    height: 75vh;
    overflow-y: auto;
}
.table-box{
  padding: 20px;
}
.box-modal{
  width: 800px;
  /* height: 350px; */
  background: white;
  /* overflow-y: auto; */
}
.pagination{
  display: flex;
  justify-content: right;
  /* height: 60px; */
  gap: 10px;
  align-items: center;
  position: relative;
  top: 20px;
  right: 30px;
}
.header{
  display: flex;gap: 10px;
}
.Message{
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 200px;
}
.imageUpload{
  width:100px;
  height:100px;
  border:1px solid #eee;
  display: flex;
  justify-content: center;
  border-radius: 6px;
  align-items: center;
}
.imageUpload:hover{
  border:1px solid rgb(49, 108, 114);
}
</style>
